var gulp = require('gulp'),
    revAll = require('gulp-rev-all')({
        hashLength: 15,
        dontRenameFile: [/[.](txt|png|jpg|font|less)$/i],
        mainfestType: 'js|css'
    }),
    del = require('del'),
    $ = require('gulp-load-plugins')();

// 管理资源文件路径集合
var config = {};

// 源资源文件路径
config['assets'] = {
    global: '*.*',
    static: 'public/**',
    less: ['public/less/invite_friend_award16521.less', 'public/less/chowhound_details16523.less', 'public/less/exchange-prize16530.less'],
    css: 'public/css/**.*',
    css_files: 'public/css/',
    font: 'public/fonts/*.*',
    img: 'public/img/*.*',
    js: 'public/js/*.*',
    html: 'views/**.html',
    html_base: 'index.html'
};

// 目标文件路径 不用替换
config['dist'] = {
    global: 'dist/',
    static: 'dist/public/',
    css: 'dist/public/css/',
    less: 'dist/public/less/',
    font: 'dist/public/font/',
    img: 'dist/public/img/',
    js: 'dist/public/js/',
    html: 'dist/views/',
    rev_json: 'dist/rev-manifest.json'
};

// 清空
gulp.task('clean', function() {
    return gulp.src([config['dist'].global], { read: false })
        .pipe($.clean());
});

// 生成文件版本
gulp.task('rev', function() {
    gulp.src(config['assets'].static)
        .pipe(revAll.revision())
        .pipe($.if('*.css', $.cssnano({
            compatibility: 'ie7' //保留ie7及以下兼容写法 类型：String 默认：''or'*' [启用兼容模式； 'ie7'：IE7兼容模式，'ie8'：IE8兼容模式，'*'：IE9+兼容模式]
        })))
        .pipe($.if('*.js', $.uglify()))
        .pipe(gulp.dest(config['dist'].static))
        .pipe(revAll.manifestFile())
        .pipe(gulp.dest(config['dist'].global))
        .on('end', function() {
            del([config['dist'].less, config['dist'].rev_json]);
        });
});

// 更新引入文件版本
gulp.task('revh', function() {
    return gulp.src([config['assets'].html_base, config['assets'].html])
        .pipe($.assetRev({
            hashLen: 15,
            verConnecter: '.'
        }))
        .pipe($.if(config['assets'].html_base, gulp.dest(config['dist'].global)))
        .pipe($.if('!' + config['assets'].html_base, gulp.dest('dist/views')));

});

// 编译less
gulp.task('less', function() {
    gulp.src(config['assets'].less)
        .pipe($.plumber({ errorHandler: $.notify.onError('Error: <%= error.message %>') }))
        .pipe($.less())
        .pipe(gulp.dest(config['assets'].css_files));
});


// 简化命令行命令(直接输入gulp); 监听事件(编译less后压缩css)
gulp.task('default', function() {
    gulp.watch(config['assets'].less, ['less']);
});

// 发布
gulp.task('build', function(cb) {
    $.sequence('clean', 'rev', 'revh', cb)
})
